"""
根据逻辑处理需要，提供数据
"""
from socket import *

ADDR = ("127.0.0.1", 8888)


class Handle:  # 具体像客户端发送请求
    def __init__(self):
        self.sock = self._connect()

    def _connect(self):
        sock = socket()
        sock.connect(ADDR)
        return sock

    def do_register(self, name, passwd):
        request = "R\t%s\t%s" % (name, passwd)
        self.sock.send(request.encode())  #
        response = self.sock.recv(128)
        if response == b'T':
            print("注册成功")
        else:
            print("注册失败")

    def do_login(self, name, passwd):
        request = "L\t%s\t%s" % (name, passwd)
        self.sock.send(request.encode())  #
        response = self.sock.recv(128)
        if response == b'T':
            print("登录成功")
            return True
        else:
            print("登录失败")

    def do_query(self):
        while True:
            word = input("要查询的单词")
            if not word or word == '##':
                break
            request = "Q\t" + word
            self.sock.send(request.encode())
            response = self.sock.recv(1024).decode()
            tmp = response.split("\t", 1)
            if tmp[0] == 'T':
                print("%s : %s" % (word, tmp[1]))
            else:
                print("没有查到该单词\n")


class DictView:
    def __init__(self):
        self.handle = Handle()

    def main(self):
        self.menue_view_1()

    def menue_view_1(self):
        while True:
            print("""
            ============welcome==========
            1.登录       2.注册      3.退出
            =============================
            """)
            cmd = input("请输入选项：")
            if cmd == "1":
                name = input("User:")
                passwd = input("Password:")
                if self.handle.do_login(name, passwd):
                    self._menu_2()
            elif cmd == "2":
                name = input("User:")
                passwd = input("Password:")
                self.handle.do_register(name, passwd)
            elif cmd == "3":
                pass
            else:
                print("请输入正确的选项！！")

    def _menu_2(self):
        while True:
            print("""
            ============welcome==========
            1.查单词    2.历史记录    3.注销
            =============================
            """)
            cmd = input("请输入选项：")
            if cmd == "1":
                self.handle.do_query()
            elif cmd == "2":
                pass
            elif cmd == "3":
                pass
            else:
                print("请输入正确的选项！！")


if __name__ == '__main__':
    dict = DictView()
    dict.main()
